package org.example.schedul;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.dao.dao.oaa.SActiveDao;
import org.example.dao.dao.order.OOrderDao;
import org.example.dao.dao.post.PLikeDao;
import org.example.dao.dao.post.PPostDao;
import org.example.dao.dao.user.ULabelDao;
import org.example.dao.dto.post.PostRedisDto;
import org.example.dao.entity.oaa.SActive;
import org.example.dao.entity.order.OOrder;
import org.example.dao.entity.post.PLike;
import org.example.dao.entity.post.PPost;
import org.example.dao.entity.post.PTheme;
import org.example.dao.entity.user.ULabel;
import org.example.exception.ParamLossErrorException;
import org.example.exception.ServerErrorException;
import org.example.skytool.commom.IdWorker;
import org.example.skytool.commom.StringUtil;
import org.example.skytool.redis.RedisUtils;
import org.example.skytool.wechat.WechatConstant;
import org.example.skytool.wechat.pay.WechatPayUtil;
import org.example.utils.market.Store.RedisStoreService;
import org.example.utils.order.OrderConstant;
import org.example.utils.order.RedisOrderService;
import org.example.utils.post.post.RedisPostService;
import org.example.utils.post.theme.RedisThemeService;
import org.example.utils.user.RedisLabelService;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 22449
 */
@Component
@Slf4j
public class MyScheduledTask {

    @Resource
    private PPostDao pPostDao;

    @Resource
    private IdWorker idWorker;

    @Resource
    private RedisPostService redisPostService;

    @Resource
    private SActiveDao sActiveDao;

    @Resource
    private ULabelDao uLabelDao;
    @Resource
    private RedisLabelService redisLabelService;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private RedisThemeService redisThemeService;
    @Resource
    private PLikeDao pLikeDao;

    @Resource
    private RedisOrderService redisOrderService;

    @Resource
    private WechatPayUtil wechatPayUtil;

    @Resource
    private OOrderDao oOrderDao;

    @Resource
    private RedisStoreService redisStoreService;

    /**
     * 定时 查询 未支付 订单
     */
    @Async("taskExecutor")
    @Scheduled(fixedRate = 1000 * 60 * 15)
    public void queryNopayOrder() {
        Set<String> set = redisOrderService.getNoPayList();
        for(String tempTradeNo : set){
            String status = wechatPayUtil.queryOrderStatus(tempTradeNo);
            if(status.equals(WechatConstant.SUCCESS)){
                //成功修改库
                redisOrderService.delNoPayOrder(tempTradeNo);
                LambdaQueryWrapper<OOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(OOrder::getIsValid,1);
                lambdaQueryWrapper.eq(OOrder::getTradeNo,tempTradeNo);
                List<OOrder> list = oOrderDao.selectList(lambdaQueryWrapper);
                for(OOrder order : list){
                    order.setStatus(OrderConstant.NO_USE);
                    order.setUpdateTime(new Date());
                    oOrderDao.updateById(order);
                }
            }else if(status.equals(WechatConstant.NOTPAY)){
                //加count值
                Long count = redisOrderService.addCount(tempTradeNo);
                if(count>20){
                    redisOrderService.delNoPayOrder(tempTradeNo);
                }
            }else if(status.equals(WechatConstant.CLOSED)){
                //删除
                redisOrderService.delNoPayOrder(tempTradeNo);
                //修改表
                LambdaQueryWrapper<OOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(OOrder::getIsValid,1);
                lambdaQueryWrapper.eq(OOrder::getTradeNo,tempTradeNo);
                List<OOrder> list = oOrderDao.selectList(lambdaQueryWrapper);
                for(OOrder order : list){
                    order.setStatus(OrderConstant.CANCEL);
                    order.setUpdateTime(new Date());
                    oOrderDao.updateById(order);
                }

            }else if(status.equals(WechatConstant.USERPAYING)){
                //转入 用户正在支付队列
                redisOrderService.delNoPayOrder(tempTradeNo);
                redisOrderService.setPayingOrder(tempTradeNo);
            }else if (status.equals(WechatConstant.REFUND)){
                //转入退款了 报错 error
                redisOrderService.delNoPayOrder(tempTradeNo);
                throw new ParamLossErrorException("微信订单状态异常");
            }else if (status.equals(WechatConstant.REVOKED)){
                //已撤销 出列
                redisOrderService.delNoPayOrder(tempTradeNo);
            }else if(status.equals(WechatConstant.PAYERROR)){
                //支付出错 报错
                redisOrderService.delNoPayOrder(tempTradeNo);
                throw new ParamLossErrorException("订单已失效，请去订单页刷新订单，或联系管理页");
            }else{
                throw new ServerErrorException("微信订单状态异常");
            }

        }
    }


    /**
     * 定时 查询 前端判断已支付 订单
     */
    @Async("taskExecutor")
    @Scheduled(fixedRate = 1000 * 60 * 5)
    public void queryPayOrder() {
        Set<String> set = redisOrderService.getPayList();
        for(String tempTradeNo : set){
            String status = wechatPayUtil.queryOrderStatus(tempTradeNo);
            if(status.equals(WechatConstant.SUCCESS)){
                //成功修改库
                redisOrderService.delPayOrder(tempTradeNo);
                LambdaQueryWrapper<OOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(OOrder::getIsValid,1);
                lambdaQueryWrapper.eq(OOrder::getTradeNo,tempTradeNo);
                List<OOrder> list = oOrderDao.selectList(lambdaQueryWrapper);
                for(OOrder order : list){
                    order.setStatus(OrderConstant.NO_USE);
                    order.setUpdateTime(new Date());
                    oOrderDao.updateById(order);
                }
            }else if(status.equals(WechatConstant.NOTPAY)){
                //加count值
                Long count =  redisOrderService.addCount(tempTradeNo);
                if(count>20){
                    redisOrderService.delPayOrder(tempTradeNo);
                }
            }else if(status.equals(WechatConstant.CLOSED)){
                //删除
                redisOrderService.delPayOrder(tempTradeNo);
                //修改表
                LambdaQueryWrapper<OOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(OOrder::getIsValid,1);
                lambdaQueryWrapper.eq(OOrder::getTradeNo,tempTradeNo);
                List<OOrder> list = oOrderDao.selectList(lambdaQueryWrapper);
                for(OOrder order : list){
                    order.setStatus(OrderConstant.CANCEL);
                    order.setUpdateTime(new Date());
                    oOrderDao.updateById(order);
                }
            }else if(status.equals(WechatConstant.USERPAYING)){
                //转入 用户正在支付队列
                redisOrderService.delPayOrder(tempTradeNo);
                redisOrderService.setPayingOrder(tempTradeNo);
            }else if (status.equals(WechatConstant.REFUND)){
                //转入退款了 报错 error
                redisOrderService.delPayOrder(tempTradeNo);
                throw new ParamLossErrorException("微信订单状态异常");
            }else if (status.equals(WechatConstant.REVOKED)){
                //已撤销 出列
                redisOrderService.delPayOrder(tempTradeNo);
            }else if(status.equals(WechatConstant.PAYERROR)){
                //支付出错 报错
                redisOrderService.delPayOrder(tempTradeNo);
                throw new ParamLossErrorException("订单已失效，请去订单页刷新订单，或联系管理页");
            }else{
                throw new ServerErrorException("微信订单状态异常");
            }
        }
    }


    /**
     * 定时 查询 正在支付中的订单
     */
    @Async("taskExecutor")
    @Scheduled(fixedRate = 1000 * 60 * 1)
    public void queryPayingOrder() {
        Set<String> set = redisOrderService.getPayingList();
        for(String tempTradeNo : set){
            String status = wechatPayUtil.queryOrderStatus(tempTradeNo);
            if(status.equals(WechatConstant.SUCCESS)){
                //成功修改库
                redisOrderService.delPayingOrder(tempTradeNo);
                LambdaQueryWrapper<OOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(OOrder::getIsValid,1);
                lambdaQueryWrapper.eq(OOrder::getTradeNo,tempTradeNo);
                List<OOrder> list = oOrderDao.selectList(lambdaQueryWrapper);
                for(OOrder order : list){
                    order.setStatus(OrderConstant.NO_USE);
                    order.setUpdateTime(new Date());
                    oOrderDao.updateById(order);
                }
            }else if(status.equals(WechatConstant.NOTPAY)){
                //加count值
                Long count = redisOrderService.addCount(tempTradeNo);
                if(count>20){
                    redisOrderService.delPayingOrder(tempTradeNo);
                }
            }else if(status.equals(WechatConstant.CLOSED)){
                //删除
                redisOrderService.delPayingOrder(tempTradeNo);
                //修改表
                LambdaQueryWrapper<OOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(OOrder::getIsValid,1);
                lambdaQueryWrapper.eq(OOrder::getTradeNo,tempTradeNo);
                List<OOrder> list = oOrderDao.selectList(lambdaQueryWrapper);
                for(OOrder order : list){
                    order.setStatus(OrderConstant.CANCEL);
                    order.setUpdateTime(new Date());
                    oOrderDao.updateById(order);
                }
            }else if(status.equals(WechatConstant.USERPAYING)){


            }else if (status.equals(WechatConstant.REFUND)){
                //转入退款了 报错 error
                redisOrderService.delPayingOrder(tempTradeNo);
                throw new ParamLossErrorException("微信订单状态异常");
            }else if (status.equals(WechatConstant.REVOKED)){
                //已撤销 出列
                redisOrderService.delPayingOrder(tempTradeNo);
            }else if(status.equals(WechatConstant.PAYERROR)){
                //支付出错 报错
                redisOrderService.delPayingOrder(tempTradeNo);
                throw new ParamLossErrorException("订单已失效，请去订单页刷新订单，或联系管理页");
            }else{
                throw new ServerErrorException("微信订单状态异常");
            }
        }
    }





    /**
     * 构造hot post total
     */
    @Async("taskExecutor")
    @Scheduled(fixedRate = 1000 * 60 * 60)
    public void createHotPostTotal() {
        //更新total
        String totalNewVersion = idWorker.nextId() + "";
        String totalKey = redisPostService.getHotPostHeader("0", totalNewVersion);
        String totalVersion = redisUtils.stringGet(redisPostService.getHotPostVersionHeader("0"));
        Long postStart = 1L;
        Long postLimit = 10L;
        Long postTotal = 0L;
        Long postCount = 0L;
        LambdaQueryWrapper<PPost> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PPost::getIsValid, 1);
        lambdaQueryWrapper.orderBy(true, false, PPost::getActive);

        do {
            IPage<PPost> postIPage = pPostDao.selectPage(new Page<>(postStart, postLimit), lambdaQueryWrapper);
            if (postTotal == 0) {
                postTotal = postIPage.getTotal();
            }
            //post加入缓存
            List<PPost> list = postIPage.getRecords();
            if (list == null || list.size() == 0) {
                break;
            }
            List<String> ids = new ArrayList<>();
            for (PPost post : list) {
                ids.add(post.getId().toString());
            }
            redisUtils.listRightAddAll(totalKey, ids.toArray(new String[0]));
            postStart++;
            if (postCount.equals(postTotal)) {
                break;
            }
            if (postStart * postLimit > postTotal) {
                postCount = postTotal;
            } else {
                postCount = postStart * postLimit;
            }
        } while (postCount <= postTotal);


        //更新version为新缓存
        redisUtils.stringSet(redisPostService.getHotPostVersionHeader("0"), totalNewVersion);
        //删除旧缓存
        if (!StringUtil.isEmpty(totalVersion)) {
            redisUtils.del(redisPostService.getHotPostHeader("0", totalVersion));
        }


        //更新分theme
        Long themeStart = 1L;
        Long themeLimit = 10L;
        Long themeTotal = 0L;
        Long themeCount = 0L;
        do {
            IPage<PTheme> themeIPage = redisThemeService.getThemeList(1, 10);
            if (themeTotal == 0) {
                themeTotal = themeIPage.getTotal();
            }
            List<PTheme> themeData = themeIPage.getRecords();
            for (PTheme theme : themeData) {
                Long themeId = theme.getId();
                String version = redisUtils.stringGet(redisPostService.getHotPostVersionHeader(themeId.toString()));
                String newVersion = idWorker.nextId() + "";
                String key = redisPostService.getHotPostHeader(themeId.toString(), newVersion);
                postStart = 1L;
                postLimit = 10L;
                postTotal = 0L;
                postCount = 0L;
                lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(PPost::getThemeId, themeId);
                lambdaQueryWrapper.eq(PPost::getIsValid, 1);
                lambdaQueryWrapper.orderBy(true, false, PPost::getActive);
                do {
                    IPage<PPost> postIPage = pPostDao.selectPage(new Page<>(postStart, postLimit), lambdaQueryWrapper);
                    if (postTotal == 0) {
                        postTotal = postIPage.getTotal();
                    }
                    //post加入缓存
                    List<PPost> list = postIPage.getRecords();
                    if (list == null || list.size() == 0) {
                        break;
                    }
                    List<String> ids = new ArrayList<>();
                    for (PPost post : list) {
                        ids.add(post.getId().toString());
                    }
                    redisUtils.listRightAddAll(key, ids.toArray(new String[0]));
                    postStart++;
                    if (postCount.equals(postTotal)) {
                        break;
                    }
                    if (postStart * postLimit > postTotal) {
                        postCount = postTotal;
                    } else {
                        postCount = postStart * postLimit;
                    }
                } while (postCount <= postTotal);
                //更新version为新缓存
                redisUtils.stringSet(redisPostService.getHotPostVersionHeader(themeId.toString()), newVersion);
                //删除旧缓存
                if (!StringUtil.isEmpty(version)) {
                    redisUtils.del(redisPostService.getHotPostHeader(themeId.toString(), version));
                }
            }
            if (themeCount.equals(themeTotal)) {
                break;
            }
            themeStart++;
            if (themeStart * themeLimit < themeTotal) {
                themeCount = themeStart * themeLimit;
            } else {
                themeCount = themeTotal;
            }
        } while (themeCount <= themeTotal);
    }

    /**
     * 存储帖子活跃度和 点赞信息
     */
    @Async("taskExecutor")
    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void storeActive() {
        Set<ZSetOperations.TypedTuple<String>> set = redisPostService.getTotalActive();
        for (ZSetOperations.TypedTuple<String> temp : set) {
            String value = temp.getValue();
            Double score = temp.getScore();
            double a = score.doubleValue();
            long b = (long) a;
            LambdaQueryWrapper<SActive> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SActive::getLinkId, value);
            SActive active = sActiveDao.selectOne(lambdaQueryWrapper);
            if (active == null) {
                active = new SActive.Builder()
                        .id(idWorker.nextId())
                        .kind("post")
                        .contentKind("文字")
                        .linkId(Long.valueOf(value))
                        .score(b)
                        .build();
                sActiveDao.insert(active);
            } else {
                active.setScore(active.getScore() + b);
                sActiveDao.updateById(active);
            }

            PPost post = pPostDao.selectById(value);
            post.setActive(post.getActive() + b);

            PostRedisDto postRedisDto = redisPostService.getCacheInfo(value);
            if (postRedisDto != null) {
                postRedisDto.setCacheData(post);
            }
            pPostDao.updateById(post);

            //存储帖子like
            Set<String> likeSet = redisPostService.getPostLikeMember(value);
            for (String likeData : likeSet) {
                String postId = value;
                String userId = likeData;
                LambdaQueryWrapper<PLike> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(PLike::getIsValid, 1);
                lambdaQueryWrapper1.eq(PLike::getUserId, userId);
                lambdaQueryWrapper1.eq(PLike::getLinkId, postId);
                PLike like = pLikeDao.selectOne(lambdaQueryWrapper1);
                if (like == null) {
                    like = new PLike();
                    like.setLinkId(Long.valueOf(postId));
                    like.setUserId(Long.valueOf(userId));
                    like.setId(idWorker.nextId());
                }
            }

        }
        redisPostService.clearTotalActive();
    }


    /**
     * 构造recommend post total
     */
    @Async("taskExecutor")
    @Scheduled(fixedRate = 1000 * 60 * 60)
    public void createRecommendPostTotal() {
        //更新total
        String totalNewVersion = idWorker.nextId() + "";
        String totalKey = redisPostService.getRecommendPostHeader("0", totalNewVersion);
        String totalVersion = redisUtils.stringGet(redisPostService.getRecommendPostVersionHeader("0"));
        Long postStart = 1L;
        Long postLimit = 10L;
        Long postTotal = 0L;
        Long postCount = 0L;
        LambdaQueryWrapper<PPost> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PPost::getIsValid, 1);
        lambdaQueryWrapper.eq(PPost::getIsRecommend, 1);
        lambdaQueryWrapper.orderBy(true, false, PPost::getCreateTime);

        do {
            IPage<PPost> postIPage = pPostDao.selectPage(new Page<>(postStart, postLimit), lambdaQueryWrapper);
            if (postTotal == 0) {
                postTotal = postIPage.getTotal();
            }
            //post加入缓存
            List<PPost> list = postIPage.getRecords();
            if (list == null || list.size() == 0) {
                break;
            }
            List<String> ids = new ArrayList<>();
            for (PPost post : list) {
                ids.add(post.getId().toString());
            }
            redisUtils.listRightAddAll(totalKey, ids.toArray(new String[0]));
            postStart++;
            if (postCount.equals(postTotal)) {
                break;
            }
            if (postStart * postLimit > postTotal) {
                postCount = postTotal;
            } else {
                postCount = postStart * postLimit;
            }
        } while (postCount <= postTotal);


        //更新version为新缓存
        redisUtils.stringSet(redisPostService.getRecommendPostVersionHeader("0"), totalNewVersion);
        //删除旧缓存
        if (!StringUtil.isEmpty(totalVersion)) {
            redisUtils.del(redisPostService.getRecommendPostHeader("0", totalVersion));
        }


        //更新分theme
        Long themeStart = 1L;
        Long themeLimit = 10L;
        Long themeTotal = 0L;
        Long themeCount = 0L;
        do {
            IPage<PTheme> themeIPage = redisThemeService.getThemeList(1, 10);
            if (themeTotal == 0) {
                themeTotal = themeIPage.getTotal();
            }
            List<PTheme> themeData = themeIPage.getRecords();
            for (PTheme theme : themeData) {
                Long themeId = theme.getId();
                String version = redisUtils.stringGet(redisPostService.getRecommendPostVersionHeader(themeId.toString()));
                String newVersion = idWorker.nextId() + "";
                String key = redisPostService.getRecommendPostHeader(themeId.toString(), newVersion);
                postStart = 1L;
                postLimit = 10L;
                postTotal = 0L;
                postCount = 0L;
                lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(PPost::getThemeId, themeId);
                lambdaQueryWrapper.eq(PPost::getIsValid, 1);
                lambdaQueryWrapper.eq(PPost::getIsRecommend, 1);
                lambdaQueryWrapper.orderBy(true, false, PPost::getCreateTime);
                do {
                    IPage<PPost> postIPage = pPostDao.selectPage(new Page<>(postStart, postLimit), lambdaQueryWrapper);
                    if (postTotal == 0) {
                        postTotal = postIPage.getTotal();
                    }
                    //post加入缓存
                    List<PPost> list = postIPage.getRecords();
                    if (list == null || list.size() == 0) {
                        break;
                    }
                    List<String> ids = new ArrayList<>();
                    for (PPost post : list) {
                        ids.add(post.getId().toString());
                    }
                    redisUtils.listRightAddAll(key, ids.toArray(new String[0]));
                    postStart++;
                    if (postCount.equals(postTotal)) {
                        break;
                    }
                    if (postStart * postLimit > postTotal) {
                        postCount = postTotal;
                    } else {
                        postCount = postStart * postLimit;
                    }
                } while (postCount <= postTotal);
                //更新version为新缓存
                redisUtils.stringSet(redisPostService.getRecommendPostVersionHeader(themeId.toString()), newVersion);
                //删除旧缓存
                if (!StringUtil.isEmpty(version)) {
                    redisUtils.del(redisPostService.getRecommendPostHeader(themeId.toString(), version));
                }
            }
            if (themeCount.equals(themeTotal)) {
                break;
            }
            themeStart++;
            if (themeStart * themeLimit < themeTotal) {
                themeCount = themeStart * themeLimit;
            } else {
                themeCount = themeTotal;
            }
        } while (themeCount <= themeTotal);
    }


    /**
     * 构造commom post total
     */
    @Async("taskExecutor")
    @Scheduled(fixedRate = 1000 * 60 * 5)
    public void createCommomPostTotal() {
        //更新total
        String totalNewVersion = idWorker.nextId() + "";
        String totalKey = redisPostService.getCommomPostHeader("0", totalNewVersion);
        String totalVersion = redisUtils.stringGet(redisPostService.getCommomPostVersionHeader("0"));
        Long postStart = 1L;
        Long postLimit = 10L;
        Long postTotal = 0L;
        Long postCount = 0L;
        LambdaQueryWrapper<PPost> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PPost::getIsValid, 1);
        lambdaQueryWrapper.orderBy(true, false, PPost::getCreateTime);

        do {
            IPage<PPost> postIPage = pPostDao.selectPage(new Page<>(postStart, postLimit), lambdaQueryWrapper);
            if (postTotal == 0) {
                postTotal = postIPage.getTotal();
            }
            //post加入缓存
            List<PPost> list = postIPage.getRecords();
            if (list == null || list.size() == 0) {
                break;
            }
            List<String> ids = new ArrayList<>();
            for (PPost post : list) {
                ids.add(post.getId().toString());
            }
            redisUtils.listRightAddAll(totalKey, ids.toArray(new String[0]));
            postStart++;
            if (postCount.equals(postTotal)) {
                break;
            }
            if (postStart * postLimit > postTotal) {
                postCount = postTotal;
            } else {
                postCount = postStart * postLimit;
            }
        } while (postCount <= postTotal);


        //更新version为新缓存
        redisUtils.stringSet(redisPostService.getCommomPostVersionHeader("0"), totalNewVersion);


        //删除旧缓存
        if (!StringUtil.isEmpty(totalVersion)) {
            redisUtils.del(redisPostService.getCommomPostHeader("0", totalVersion));
        }


        //更新分theme
        Long themeStart = 1L;
        Long themeLimit = 10L;
        Long themeTotal = 0L;
        Long themeCount = 0L;
        do {
            IPage<PTheme> themeIPage = redisThemeService.getThemeList(1, 10);
            if (themeTotal == 0) {
                themeTotal = themeIPage.getTotal();
            }
            List<PTheme> themeData = themeIPage.getRecords();
            for (PTheme theme : themeData) {
                Long themeId = theme.getId();
                String version = redisUtils.stringGet(redisPostService.getCommomPostVersionHeader(themeId.toString()));
                String newVersion = idWorker.nextId() + "";
                String key = redisPostService.getCommomPostHeader(themeId.toString(), newVersion);
                postStart = 1L;
                postLimit = 10L;
                postTotal = 0L;
                postCount = 0L;
                lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(PPost::getThemeId, themeId);
                lambdaQueryWrapper.eq(PPost::getIsValid, 1);
                lambdaQueryWrapper.orderBy(true, false, PPost::getCreateTime);
                do {
                    IPage<PPost> postIPage = pPostDao.selectPage(new Page<>(postStart, postLimit), lambdaQueryWrapper);
                    if (postTotal == 0) {
                        postTotal = postIPage.getTotal();
                    }
                    //post加入缓存
                    List<PPost> list = postIPage.getRecords();
                    if (list == null || list.size() == 0) {
                        break;
                    }
                    List<String> ids = new ArrayList<>();
                    for (PPost post : list) {
                        ids.add(post.getId().toString());
                    }
                    redisUtils.listRightAddAll(key, ids.toArray(new String[0]));
                    postStart++;
                    if (postCount.equals(postTotal)) {
                        break;
                    }
                    if (postStart * postLimit > postTotal) {
                        postCount = postTotal;
                    } else {
                        postCount = postStart * postLimit;
                    }
                } while (postCount <= postTotal);
                //更新version为新缓存
                redisUtils.stringSet(redisPostService.getCommomPostVersionHeader(themeId.toString()), newVersion);
                //删除旧缓存
                if (!StringUtil.isEmpty(version)) {
                    redisUtils.del(redisPostService.getCommomPostHeader(themeId.toString(), version));
                }
            }
            if (themeCount.equals(themeTotal)) {
                break;
            }
            themeStart++;
            if (themeStart * themeLimit < themeTotal) {
                themeCount = themeStart * themeLimit;
            } else {
                themeCount = themeTotal;
            }
        } while (themeCount <= themeTotal);
    }


    /**
     * 构造Label缓存
     */
    @Async("taskExecutor")
    @Scheduled(fixedRate = 1000 * 60 * 60 * 24)
    public void createLabelTotal() {
        String version = redisUtils.stringGet(redisLabelService.getLabelTotalListKeyVersion());
        String newVersion = idWorker.nextId() + "";
        LambdaQueryWrapper<ULabel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ULabel::getIsValid, 1);
        Long total = 0L;
        Long start = 1L;
        Long limit = 50L;
        Long count = 0L;
        do {
            IPage<ULabel> page = uLabelDao.selectPage(new Page<>(start, limit), lambdaQueryWrapper);
            if (total == 0) {
                total = page.getTotal();
            }
            List<ULabel> list = page.getRecords();
            redisLabelService.setLabelTotalList(list, newVersion);
            start++;
            if (count.equals(total)) {
                break;
            }
            if (start * limit > total) {
                count = total;
            } else {
                count = start * limit;
            }
        } while (count <= total);

        redisUtils.stringSet(redisLabelService.getLabelTotalListKeyVersion(), newVersion);

        if (!StringUtil.isEmpty(version)) {
            redisLabelService.delLabelTotalList(version);
        }

    }

    /**
     * 构建所有店铺缓存
     */
    @Async("taskExecutor")
    @Scheduled(fixedRate = 1000 * 60 * 60 * 24)
    public void createStoreIds() {
        redisStoreService.createStoreIds();
    }

}